<?php
	class ControllerCoreUsertype extends Controller
	{
		public function index()
		{
			$this->load->model("core/usertype");
			$this->load->model("core/user");
			$this->load->model("core/module");
			$this->load->model("core/sitemap");
			$this->load->model("common/control");
			
			$user=$this->model_core_user->getUser($this->session->data['userid']);
			//echo $user[0]['usertypeid'];
			if($user[0]['usertypeid']!=1)
				$this->response->redirect("index.php?route=error/permission");
			//echo $this->session->data['userid'];
			
			switch($this->request->get['formtype'])
			{
				case "":
						if ( strcasecmp( @ $_SERVER['REQUEST_METHOD'], 'POST' ) == 0 )
						{
							if(isset($this->request->post['del_all']))
							{
								$listid=$this->request->post['del'];
								$arrChecked=array();
								foreach($listid as $id)
								{
									if($this->validateDelete($id))
									{	
										array_push($arrChecked, $id);
									}
								}
								$this->delete($arrChecked);
							}
						}
						$this->getList();
						break;
				case "add":
						if ( strcasecmp( @ $_SERVER['REQUEST_METHOD'], 'POST' ) == 0 )
						{
							if(isset($this->request->post['save']))
							{
								if($this->validateForm())
								{
									$this->insert();
									$this->response->redirect("index.php?route=core/usertype");
								}
							}
						}
						$this->getForm();
						break;
				case "edit":
						if ( strcasecmp( @ $_SERVER['REQUEST_METHOD'], 'POST' ) == 0 )
						{
							if(isset($this->request->post['save']))
							{
								
									$this->update();
									$this->response->redirect("index.php?route=core/usertype");
								
							}
						}
						//$this->updateList();
						$this->getForm();
						break;
				
				case "delete":
						if( strcasecmp( @ $_SERVER['REQUEST_METHOD'], 'GET' ) == 0 )
						{
							
								$id=$this->request->get['id'];
								$arrChecked=array();
								
									array_push($arrChecked, $id);
							
								$this->delete($arrChecked);
							
						}
						$this->response->redirect("index.php?route=core/usertype");
						$this->getList();
						break;
			}
			$this->id="content";
			$this->render();			
		}

		function getList()
		{
			$this->user->setControl('add','btnAdd');
			$this->user->setControl('addMember','btnAddMember');
			$this->user->setControl('edit','btnEdit');
			$this->user->setControl('delete','btnDelete');
			
			$list = array();
			$this->model_core_usertype->getTreeUserType("",$list);
			
			$this->data['btnAdd'] = $this->model_common_control->getButton("btnAdd","btnAdd",$this->document->text['button_addnewgroup'],"?route=core/usertype&formtype=add");
			foreach($list as $resutl )
			{
				$deep=$this->model_core_usertype->getDeep($resutl['usertypeid']);
				$parent=$this->model_core_usertype->getUserType($resutl['UserTypeParent']);
				
				if($parent[0]['usertypename'] == "")
				{
					$btnAddMember = $this->model_common_control->getControlAddMember("btnAddMember","btnAddMember","[Add more user type]","?route=core/usertype&formtype=add&id=".$resutl['usertypeid']);
				}
				else
				{
					$btnAddMember = "";
				}
				$controlEdit = $this->model_common_control->getControlEdit("controlEdit","controlEdit","[Edit]","?route=core/usertype&formtype=edit&id=".$resutl['usertypeid']);
				$controlDelete = $this->model_common_control->getControlDelete("controlDelete","controlDelete","[Delete]","?route=core/usertype&formtype=delete&id=".$resutl['usertypeid']);
				
				
				$this->data["usertypes"][]=array(
											'usertypeid'=>$resutl['usertypeid'],
											'usertypename'=>$resutl['usertypename'],
											'Prefix'=>$this->string->getPrefix("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;+&nbsp;&nbsp;&nbsp;",$deep -1),
											'Deep'=>$deep + 1,
											'UserTypeParent'=>$parent[0]['usertypename'],
											'UserTypeParentID'=>$parent[0]['usertypeid'],
											'btnAddMember' => $btnAddMember ,
											'btnEdit' => $controlEdit,
											'btnDelete' => $controlDelete
											);
			}
			
			
			
			
			
			$this->template="core/usertype_list.tpl";
			$this->layout="layout/center";	
		}
		
	
		function getForm()
		{
			$list = array();
			$this->model_core_usertype->getTreeUserType("",$list);
			
			$this->data['showParent'] = "display:none";
			
			if($this->request->get['formtype'] == 'edit')
			{
				$usertypeid=$this->request->get['id'];
				if($usertypeid != ""){
					$result=$this->model_core_usertype->getUsertype($usertypeid);
					$this->data['UserType']=array(
							'usertypeid'=>$result[0]['usertypeid'],
							'usertypename'=>$result[0]['usertypename'],
							'UserTypeParent'=>$result[0]['UserTypeParent'],
							'permission'=>$result[0]['permission']
					);
					$UserTypeParent = $this->data['UserType']['UserTypeParent'];
				}
				
				$UserTypeParent = $this->data['UserType']['UserTypeParent'];
				
			}
			else
			{
				$UserTypeParent = $this->request->get['id'];
			}
			
			foreach($list as $resutl )
			{
				$deep=$this->model_core_usertype->getDeep($resutl['usertypeid']);
				$parent=$this->model_core_usertype->getUserType($resutl['UserTypeParent']);
				$strSelected = "";
				if($resutl['usertypeid'] == $UserTypeParent) $strSelected = 'selected="selected"';
				$this->data["usertypes"][]=array(
											'usertypeid'=>$resutl['usertypeid'],
											'usertypename'=>$resutl['usertypename'],
											'Prefix'=>$this->string->getPrefix("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;",$deep -1),
											'Deep'=>$deep + 1,
											'UserTypeParent'=>$parent[0]['UserTypeParent'],
											'Selected' => $strSelected
											);
				if($UserTypeParent != "" && $strSelected != "") {
					$this->data['parentname'] = $resutl['usertypename'];
				}
				
			}
			
			if($this->data['parentname'] == "" && $this->data['showParent'] == "display:none" ) {
				$this->data['parentname'] = "root";
			}
			
			
			$this->getPermissionData();
		
			//$this->cache();
			$this->template = 'core/usertype_form.tpl';
			$this->layout="layout/center";
		}
	
		function cache()
		{
			$this->data['cache']['usertypename']=$this->request->post['usertypename'];
		}
		
		function updateList()
		{
			$usertypeid=$this->request->get['id'];
			$result=$this->model_core_usertype->getUsertype($usertypeid);
			$this->data['UserType']=array(
					'usertypeid'=>$result[0]['usertypeid'],
					'usertypename'=>$result[0]['usertypename']
			);
		}
		
		function validateForm()
		{	
			$usertypename = $this->request->post['usertypename'];
			//require
			if($usertypename=='')
				$this->data['require']='Bạn chưa nhập tên loại người dùng';
			//unique usertypename
			$results=$this->model_core_usertype->getAllUsertype();
			foreach($results as $result)
			{
				if($usertypename==$result['usertypename'])
				{
					$this->data['unique']='Tên loại người dùng này đã tồn tại';
					break;
				}
			}
			if($this->data['require']!=null||$this->data['unique']!=null)
				return false;
			else
				return true;
		}
		
		function validateDelete($usertypeid)
		{
			$flag=false;
			$results=$this->model_core_usertype->getUsertypeNoRelation($usertypeid);
			foreach($results as $result)
			{
				if($usertypeid==$result['usertypeid'])
				{
					$flag=true;
					break;
				}
			}
			return $flag;
		}
		
		function insert()
		{
				$data['usertypeid']=$this->model_core_usertype->nextID();
				$data['usertypename']=$this->request->post['usertypename'];
				$data['UserTypeParent']=$this->request->post['UserTypeParent'];
				$data['permission'] = $this->getPermissionJSONString();
				$this->model_core_usertype->insertUsertype($data);	
		}
		
		function delete($data)
		{
				$this->model_core_usertype->deleteUsertype($data);	
		}
		
		
		function update()
		{
			$data['usertypeid']=$this->request->post['usertypeid'];
			$data['usertypename']=$this->request->post['usertypename'];
			$data['UserTypeParent']=$this->request->post['UserTypeParent'];
			$data['permission'] = $this->getPermissionJSONString();
			$this->model_core_usertype->updateUsertype($data);	
		}
		
//BEGIN PHAN QUYEN
	function getPermissionData()
	{
		$this->data['modules'] = array();
		$moduleid = "";
		
		//Parent variables
		$strParentPermission = ""; //Chuoi Permission của User Parent
		$arrParentJSON = array();
		$arrParentModules_Filter = array();
		$arrParentPermision = array();
		$arrParentSitemap = array();
		
		//UserType Permission Variable
		$strPermission = "";
		$arrJSON = array();
		$arrModule = array();
		
		
		
		//Lay Permission của Parent		
		$parentid = ""; //User Parent ID
		$parent = array(); //User Parent
		
		if($this->request->get['id'] != '')
		{
			switch ($this->request->get['formtype'])
			{
				case 'add':
					$parentid = $this->request->get['id'];
				break;
				case 'edit':
					$parentid = $this->data['UserType']['UserTypeParent'];
				break;
			}
			
			$parent = $this->model_core_usertype->getUsertype($parentid);
			
			$strParentPermission = $parent[0]['permission']; // Ket qua
			if($strParentPermission != "")
			{
				$arrParentJSON = $this->user->_getJSONArray($strParentPermission);
				$arrParentModules_Filter = $this->user->_getModules_Filter($arrParentJSON);
			}
			
		}
		
		//Lay Permission của UserType
		if($this->data['UserType']['permission'] != "")
		{
			$strPermission = $this->data['UserType']['permission'];
			$arrJSON = $this->user->_getJSONArray($strPermission);
			$arrModule = $this->user->_getModules($arrJSON);
			
		}
		
		
		//Lay cac modules cho phan quyen can thiet
		if(count($arrParentModules_Filter) > 0){
			$strIn = "'".implode("','",$arrParentModules_Filter)."'";
			$this->data['modules'] = $this->model_core_module->getModulesIn($strIn);
		}else
		{
			$this->data['modules'] = $this->model_core_module->getModules();
		}
		
		
		//Duyet Modules	
		
			
		for( $i=0; $i<count($this->data['modules']); $i++)
		{
			//Module ID
			$moduleid = $this->data['modules'][$i]['moduleid'];
						
			$arrParentPermission = $this->user->_getPermissions($moduleid, $arrParentJSON);
			$arrParentSitemap = $this->user->_getSitemaps($moduleid, $arrParentJSON);
			
			$arrPermission = $this->user->_getPermissions($moduleid, $arrJSON);
			$arrSitemap = $this->user->_getSitemaps($moduleid, $arrJSON);
			
			//Neu root hien het, ko phai root thi loc
			$arrModulePermission = array();
			$arrModuleSitemap = array();
			if($parentid == "" || $parentid == 0)
			{
				$arrModulePermission = $this->user->_getJSONArray($this->data['modules'][$i]['permission']);
				$arrModuleSitemap = $this->model_core_sitemap->getSiteMapByModule($moduleid);	
			}
			else
			{
				$arrModulePermission = $arrParentPermission;
				$arrTemp = $this->model_core_sitemap->getSiteMapByModule($moduleid);
				foreach($arrTemp as $row)
				{
					if($this->string->inArray($row['sitemapid'],$arrParentSitemap) > -1)
					{
						array_push($arrModuleSitemap, $row);
					} 
				}
			}
			
			//Duyet tung phan tu trong list Module Permission
			$this->data['modules'][$i]['permissions'] = array();
			foreach($arrModulePermission as $p)
			{
				$strChecked = "";
				
				//Kiem tra trong data
				if($this->string->inArray($p, $arrPermission) > -1) $strChecked = "Checked = Checked";
				
				//Kiem tra post 
				$arrPost = $this->request->post['permission'.$moduleid];
				if($this->string->inArray($p, $arrPost) > -1) $strChecked = "Checked = Checked";
				
				//Add
				$this->data['modules'][$i]['permissions'][] = array($p,$strChecked);
			}
			
			
			//Duyet tung phan tu trong list Module Sitemap
			$this->data['modules'][$i]['Sitemaps'] = array();
			foreach($arrModuleSitemap as $s)
			{
				$strChecked = "";
				
				//Kiem tra trong data
				if($this->string->inArray($s['sitemapid'], $arrSitemap) > -1) $strChecked = "Checked = Checked";
				
				//Kiem tra post 
				$arrPost = $this->request->post['sitemap'.$moduleid];
				if($this->string->inArray($s['sitemapid'], $arrPost) > -1) $strChecked = "Checked = Checked";
				
				//Add
				$this->data['modules'][$i]['Sitemaps'][] = array($s,$strChecked);
			}

		}
	}
		
		
	function getPermissionJSONString()
	{
		$arrPermission = array();
					
		$arrPermission[0] = array();
		
		$this->data['modules'] = $this->model_core_module->getModules();
		
		$index = 0;
		
		foreach($this->data['modules'] as $module)
		{
			array_push($arrPermission[0],$module['moduleid']);
			
			
			$index += 1;
			$arrPermission[$index] = array();
					
			$arr = $this->request->post['permission'.$module['moduleid']];
			
			$arrPermission[$index][0]=array();
			if(count($arr) > 0)
			{
				foreach($arr as $key => $value)
				{
					array_push($arrPermission[$index][0], $value);
				}
			}
			
			$arr = $this->request->post['sitemap'.$module['moduleid']];

			$arrPermission[$index][1]=array();
			if(count($arr) > 0)
			{
				foreach($arr as $key => $value)
				{
					array_push($arrPermission[$index][1], $value);
				}
			}
		}
		
		$strPermission = $this->json->encode($arrPermission);
		
		return $strPermission;
	}
//END PHAN QUYEN









		
	}
?>